import json
import sys
import os
from sqlalchemy.orm import Session
from database import get_db, engine
from crud import create_question
from schemas import QuestionCreate

def import_questions_from_json(json_file_path):
    """从JSON文件导入题目到数据库"""
    db = None
    try:
        # 读取JSON文件
        with open(json_file_path, 'r', encoding='utf-8') as f:
            questions_data = json.load(f)
        
        # 获取数据库会话
        from config import Config
        from sqlalchemy import create_engine
        from sqlalchemy.orm import sessionmaker
        from database import Base
        engine = create_engine(Config.DATABASE_URL)
        # 创建表
        Base.metadata.create_all(bind=engine)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        db = SessionLocal()
        
        imported_count = 0
        
        for question_data in questions_data:
            # 转换数据格式
            question_create = QuestionCreate(
                questionContent=question_data['question'],
                optionA=question_data['options']['A'],
                optionB=question_data['options']['B'],
                optionC=question_data['options']['C'],
                optionD=question_data['options']['D'],
                answer=question_data['answer'],
                knowledgePoint=question_data['knowledge_point']
            )
            
            # 创建题目
            try:
                create_question(db, question_create)
                imported_count += 1
                print(f"导入题目 {imported_count}: {question_data['question'][:30]}...")
            except Exception as e:
                print(f"导入题目失败: {e}")
                continue
        
        print(f"\n成功导入 {imported_count} 道题目！")
        
    except Exception as e:
        print(f"导入失败: {e}")
    finally:
        if db:
            db.close()

if __name__ == "__main__":
    json_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), "sample_questions.json")
    import_questions_from_json(json_file)